package com.zdsoft.p2p.user.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.WebRequest;

import com.zdsoft.p2p.user.domain.User;
import com.zdsoft.rock.common.AppException;
import com.zdsoft.rock.common.model.domain.ResponseMsg;
/**
 * 控制器增强
 * @author yhm
 *
 */
@ControllerAdvice
public class CustomerController {
	
	private Logger logger=LoggerFactory.getLogger(getClass());
	@ModelAttribute  
    public User newUser() {  
		logger.debug("应用到所有@RequestMapping注解方法，在其执行之前把返回值放入Model"); 
		logger.debug("客户把登录用户信息放到这里");
        return new User();  
    }  
  
    @InitBinder  
    public void initBinder(WebDataBinder binder,WebRequest request) {  
    	logger.debug("应用到所有@RequestMapping注解方法，在其执行之前初始化数据绑定器");  
    }  
  
    @ExceptionHandler(Exception.class)  
    @ResponseStatus(HttpStatus.UNAUTHORIZED) 
    @ResponseBody
    public ResponseMsg<String> processUnauthenticatedException(NativeWebRequest request, Exception e) {  
    	logger.debug("应用到所有@RequestMapping注解的方法，在其抛出Exception异常时执行");
    	ResponseMsg<String> msg=new ResponseMsg<String>();
    	msg.failed(e.getMessage());
    	logger.debug("请求抛出异常:{}",e);
    	return msg;
        //return "viewName"; //返回一个逻辑视图名  
    }
    
    /**
     * 遇到AppException异常时返回失败的Json串
     * @param app
     * @return
     */
    @ExceptionHandler(AppException.class)
    @ResponseBody
    public ResponseMsg<String> processAppException(WebRequest request,AppException app){
    	logger.debug("应用到所有@RequestMapping注解的方法,在其抛出AppException异常时执行");
    	ResponseMsg<String> msg=new ResponseMsg<String>();
    	msg.failed(app.getMessage());
    	return msg;
    }
}
